/**
 * 文件压缩
 * 2019-12-12 15:05
 * author @creatnl
 */

import http = require('http')
import url = require('url')
import path = require('path')
import fs = require('fs')
import zlib = require('zlib')
import mime = require('mime')

import { SSR } from './ssr'
console.log(SSR.val)

//文件资源路径
const root = path.resolve(process.argv[2] || '.') + '/public/'

// 允许压缩的文件类型
const FILE_TYPES = require('../config/compress-file-types.json')


export function loadContent (request: http.IncomingMessage, response: http.ServerResponse) {
  //获得浏览器编码类型
  const acceptEncoding: string = request.headers['accept-encoding'] ? request.headers['accept-encoding'].toString() : ''
  // 获得URL的path，类似 '/css/bootstrap.css':
  let pathname: string = url.parse(request.url).pathname
  pathname = pathname == '/' ? '/index.html' : pathname
  // 获得对应的本地文件路径，类似 '/srv/www/css/bootstrap.css':
  const filepath: string = path.join(root, pathname)
  // 获取文件状态:
  fs.stat(filepath, (err, stats) => {
    // 出错了或者文件不存在:
    // 发送404响应:
    if (err || !stats.isFile()) {
      response.writeHead(404)
      response.end('404 Not Found')
      // 加上return 否则程序会崩溃
      return
    }

    // 判断请求的文件类型是否需要压缩
    const FILE_TYPE_CHECK = FILE_TYPES.indexOf(mime.lookup(filepath)) >= 0

    //返回类型、缓存时间
    let content = { 'Cache-Control': 'max-age=31536000, public', 'Content-type': mime.lookup(filepath) }
    let raw = fs.createReadStream(filepath)
    console.log(pathname, raw)
    //将文件流导向response:
    if (FILE_TYPE_CHECK && acceptEncoding.match(/\bgzip\b/)) {
      content['Content-Encoding'] = 'gzip'
      response.writeHead(200, content)
      raw.pipe(zlib.createGzip()).pipe(response)
    } else if (FILE_TYPE_CHECK && acceptEncoding.match(/\bdeflate\b/)) {
      content['Content-Encoding'] = 'deflate'
      response.writeHead(200, content)
      raw.pipe(zlib.createDeflate()).pipe(response)
    } else {
      response.writeHead(200, content)
      raw.pipe(response)
    }
  })

}